package xcmg.device.service.company;

import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.DealerVehicleDO;
import xcmg.device.dao.entity.company.DealerVehicleLogDO;
import xcmg.device.dao.entity.sale.SalesBillDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.company.DealerVehicleLogDOMapper;
import xcmg.device.dao.mapper.company.DealerVehicleMapper;
import xcmg.device.dao.mapper.sale.SalesBillMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.FileUtil;
import xcmg.device.service.agent.ServiceBasicDataAgentService;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.company.CompanyDealerVO;
import xcmg.device.service.vo.company.DealerVehicleInfoVO;
import xcmg.device.service.vo.company.DealerVehicleVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wrg on 2019/4/19.
 */
@Service
public class DealerVehicleService {
    @Autowired
    private DealerVehicleMapper dealerVehicleMapper;
    @Autowired
    private FastGenClient genClient;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Value("${spring.file.download.path}")
    private String filePath;

    private String templateExcelFileName = "DealerVehicle.xls";
    @Autowired
    private ServiceBasicDataAgentService serviceBasicDataAgentService;
    @Autowired
    private SalesBillMapper salesBillMapper;
    @Autowired
    private DealerVehicleLogDOMapper dealerVehicleLogDOMapper;

    public PageCommonVO list(SearchCommonVO<DealerVehicleVO> condition) {
        PageHelperPlus.orderBy("CREATE_DATE, ORG_ID ,ID desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<DealerVehicleDO> doList = dealerVehicleMapper.list(condition.getFilters());
        List<DealerVehicleVO> voList = new ArrayList<>();
        getVOList(doList, voList);
        PageCommonVO<DealerVehicleVO> pageCommonVO = new PageCommonVO<>();
        pageCommonVO.setPageInfo(new PageInfo<>(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }


    public PageCommonVO saleBillDealerList(SearchCommonVO<CompanyDealerVO> condition) {
        CompanyDealerVO filters = condition.getFilters();
        String orgId = filters.getOrgId();
        String companyName = filters.getCompanyName();

        PageCommonVO pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<DealerVehicleDO> doList = companyDealerMapper.saleBillDealerList(orgId, companyName);
        for (DealerVehicleDO vehicle : doList) {//进出口设置默认值
            vehicle.setBrandCode("jinchukou-default");
            vehicle.setBrandName("jinchukou-default");
            vehicle.setModel("jinchukou-default");
            vehicle.setCarNo("jinchukou-default");
            vehicle.setMaintenanceSendAmount(BigDecimal.ZERO);
            vehicle.setUniversalSendAmount(BigDecimal.ZERO);
            vehicle.setMaintenanceUseAmount(BigDecimal.ZERO);
            vehicle.setUniversalUseAmount(BigDecimal.ZERO);
            vehicle.setMaintenanceLaveAmount(BigDecimal.ZERO);
            vehicle.setUniversalLaveAmount(BigDecimal.ZERO);
            vehicle.setWarrantStatus(1);
        }
        List<DealerVehicleVO> voList = new ArrayList<>();
        getVOList(doList, voList);
        pageCommonVO.setPageInfo(new PageInfo(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    public PageCommonVO notDeactivatedList(SearchCommonVO<DealerVehicleVO> condition) {
        PageHelperPlus.orderBy("CREATE_DATE, ORG_ID ,ID desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<DealerVehicleDO> doList = dealerVehicleMapper.notDeactivatedList(condition.getFilters());
        List<DealerVehicleVO> voList = new ArrayList<>();
        getVOList(doList, voList);
        PageCommonVO<DealerVehicleVO> pageCommonVO = new PageCommonVO<>();
        pageCommonVO.setPageInfo(new PageInfo<>(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    private void getVOList(List<DealerVehicleDO> doList, List<DealerVehicleVO> voList) {
        doList.forEach(dealerVehicleDO -> {
            DealerVehicleVO dealerVehicleVO = new DealerVehicleVO();
            BeanUtils.copyProperties(dealerVehicleDO, dealerVehicleVO);
            //获取客户code
            if (StringUtils.isNotBlank(dealerVehicleDO.getClientId())) {
                CompanyDealerDO companyDealerDO = companyDealerMapper.item(Long.valueOf(dealerVehicleDO.getClientId()));
                if (null != companyDealerDO) {
                    dealerVehicleVO.setClientCode(companyDealerDO.getDealerCode());
                    dealerVehicleVO.setDealerOrgId(companyDealerDO.getDealerOrgId());
                }
            } else {
                CompanyDealerDO companyDealerDO = companyDealerMapper.getDealerByOrgIdCompanyName(dealerVehicleDO.getOrgId(), dealerVehicleDO.getClientName());
                if (null != companyDealerDO) {
                    dealerVehicleVO.setClientCode(companyDealerDO.getDealerCode());
                    dealerVehicleVO.setDealerOrgId(companyDealerDO.getDealerOrgId());
                }
            }

            voList.add(dealerVehicleVO);
        });
    }

    public PageCommonVO getVehicleList(SearchCommonVO<DealerVehicleVO> condition) {
        String orgId = condition.getFilters().getOrgId();

        PageHelperPlus.orderBy("CREATE_DATE ORG_ID ID desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        // 获取用户信息
        List<DealerVehicleDO> doList = dealerVehicleMapper.getVehicleList(condition.getFilters());
        List<DealerVehicleInfoVO> voList = new ArrayList<>();
        doList.forEach(dealerVehicleDO -> {
            String clientName = dealerVehicleDO.getClientName();
            String clientNo = dealerVehicleDO.getClientNo();
            String clientId = dealerVehicleDO.getId();
            DealerVehicleInfoVO dealerVehicleInfoVO = new DealerVehicleInfoVO();
            dealerVehicleInfoVO.setClientId(clientId);
            dealerVehicleInfoVO.setClientName(clientName);
            dealerVehicleInfoVO.setClientNo(clientNo);
            List<DealerVehicleDO> dealerVehicleDOList = dealerVehicleMapper.selectByClientName(clientName, orgId);
            List<DealerVehicleVO> detailsList = new ArrayList<>();
            dealerVehicleDOList.forEach(x -> {
                DealerVehicleVO dealerVehicleVO = new DealerVehicleVO();
                BeanUtils.copyProperties(dealerVehicleDO, dealerVehicleVO);
                detailsList.add(dealerVehicleVO);
            });
            dealerVehicleInfoVO.setDetailsList(detailsList);
            voList.add(dealerVehicleInfoVO);
        });
        PageCommonVO<DealerVehicleInfoVO> pageCommonVO = new PageCommonVO<>();
        pageCommonVO.setPageInfo(new PageInfo<>(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }


    public ErrorCode insert(DealerVehicleVO dealerVehicleVO, String userId, String orgId) {
        DealerVehicleDO dealerVehicleDO = new DealerVehicleDO();
        BeanUtils.copyProperties(dealerVehicleVO, dealerVehicleDO);
        dealerVehicleDO.setCreateDate(new Date());
        dealerVehicleDO.setUpdateDate(new Date());
        dealerVehicleDO.setCreateId(userId);
        dealerVehicleDO.setUpdateId(userId);
        dealerVehicleDO.setOrgId(orgId);
        Integer nameCount = dealerVehicleMapper.vehicleCount(dealerVehicleDO);
        if (nameCount > 0) {
            return ErrorCode.VehicleInfoPresence;
        }
        String id = genClient.newGuidText().getValue();
        if (StringUtils.isBlank(id)) {
            return ErrorCode.PrimaryKeyGenerationFailed;
        }
        dealerVehicleDO.setId(id);
        return dealerVehicleMapper.insertSelective(dealerVehicleDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    public ErrorCode update(DealerVehicleVO dealerVehicleVO, String userId,String userName) {
        DealerVehicleDO dealerVehicleDO1 = dealerVehicleMapper.selectByPrimaryKey(dealerVehicleVO.getId());
        if (null == dealerVehicleDO1) {
            return ErrorCode.IllegalArument;
        }

        DealerVehicleDO dealerVehicleDO = new DealerVehicleDO();
        BeanUtils.copyProperties(dealerVehicleVO,dealerVehicleDO);
        dealerVehicleDO.setId(dealerVehicleVO.getId());
        dealerVehicleDO.setBrandCode(dealerVehicleVO.getBrandCode());
        dealerVehicleDO.setBrandName(dealerVehicleVO.getBrandName());
        dealerVehicleDO.setUpdateId(userId);
        dealerVehicleDO.setUpdateDate(new Date());
        dealerVehicleDO.setOrgId(dealerVehicleVO.getOrgId());
        dealerVehicleDO.setCarNo(dealerVehicleVO.getCarNo());
        dealerVehicleDO.setModel(dealerVehicleVO.getModel());
        dealerVehicleDO.setClientName(dealerVehicleVO.getClientName());
        dealerVehicleDO.setIsDisable(dealerVehicleVO.getIsDisable());
        dealerVehicleDO.setRemark(dealerVehicleVO.getRemark());
        Integer nameCount = dealerVehicleMapper.vehicleCount(dealerVehicleDO);
        if (nameCount > 0) {
            return ErrorCode.LevelNameDuplicated;
        }
        boolean success = dealerVehicleMapper.updateByPrimaryKeySelective(dealerVehicleDO) > 0;
        if (success) {
            BigDecimal universalUpdateAmount = dealerVehicleVO.getUniversalUpdateAmount()== null ? BigDecimal.ZERO:dealerVehicleVO.getUniversalUpdateAmount();
            BigDecimal maintenanceUpdateAmount = dealerVehicleVO.getMaintenanceUpdateAmount()== null ? BigDecimal.ZERO:dealerVehicleVO.getMaintenanceUpdateAmount();
            if (maintenanceUpdateAmount.compareTo(BigDecimal.ZERO) != 0 &&
                    universalUpdateAmount.compareTo(BigDecimal.ZERO) != 0){
                DealerVehicleLogDO record = new DealerVehicleLogDO();
                record.setCreateId(userId);
                record.setCreateName(userName);
                record.setCreateTime(new Date());
                record.setGeneralQuota(universalUpdateAmount);
                record.setId(genClient.newGuidText().getValue());
                record.setOrgId(dealerVehicleVO.getOrgId());
                record.setMaintenanceQuota(maintenanceUpdateAmount);
                success = dealerVehicleLogDOMapper.insertSelective(record) > 0;
            }
        }
        return success ? ErrorCode.Success : ErrorCode.Failure;
    }

    public ErrorCode disable(DealerVehicleVO dealerVehicleVO, String userId) {
        Integer count = dealerVehicleMapper.existCount(dealerVehicleVO.getId());
        if (count <= 0) {
            return ErrorCode.IllegalArument;
        }
        DealerVehicleDO dealerVehicleDO = new DealerVehicleDO();
        dealerVehicleDO.setId(dealerVehicleVO.getId());
        dealerVehicleDO.setUpdateId(userId);
        dealerVehicleDO.setUpdateDate(new Date());
        dealerVehicleDO.setIsDisable(dealerVehicleVO.getIsDisable());
        return dealerVehicleMapper.disable(dealerVehicleDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    public DealerVehicleVO getDetail(String id) {
        DealerVehicleDO dealerVehicleDO = dealerVehicleMapper.selectByPrimaryKey(id);
        DealerVehicleVO dealerVehicleVO = new DealerVehicleVO();
        BeanUtils.copyProperties(dealerVehicleDO, dealerVehicleVO);
        return dealerVehicleVO;
    }

    /**
     * 导出全部车辆信息
     *
     * @param dealerVehicleVO 查询条件VO
     * @throws Exception Exception
     */
    public void exportAll(DealerVehicleVO dealerVehicleVO) throws Exception {
        PageHelperPlus.orderBy("CREATE_DATE, ORG_ID, ID desc");
        List<DealerVehicleDO> dealerVehicleDOList = dealerVehicleMapper.list(dealerVehicleVO);
        invokeExport(dealerVehicleDOList);
    }

    /**
     * 车辆信息导出
     *
     * @param dealerVehicleDOList
     * @throws Exception
     */
    private void invokeExport(List<DealerVehicleDO> dealerVehicleDOList) throws Exception {
        String title = "客户车辆信息导出";
        String[] rowsName = new String[]{"序号", "客户", "品牌", "机型", "车号", "整机赠送额度(保养)", "整机赠送额度(通用)",
                "已用额度(保养)", "已用额度(通用)", "剩余额度(保养)", "剩余额度(通用)", "是否停用", "备注"};
        List<Object[]> dataList = new ArrayList<>();

        if (dealerVehicleDOList.isEmpty()) {
            ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
            exportUtil.export(response);
            return;
        }

        int i = 1;
        for (DealerVehicleDO dealerVehicleDO : dealerVehicleDOList) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = i;
            objs[1] = dealerVehicleDO.getClientName();
            objs[2] = dealerVehicleDO.getBrandName();
            objs[3] = dealerVehicleDO.getModel();
            objs[4] = dealerVehicleDO.getCarNo();
            objs[5] = dealerVehicleDO.getMaintenanceSendAmount();
            objs[6] = dealerVehicleDO.getUniversalSendAmount();
            objs[7] = dealerVehicleDO.getMaintenanceUseAmount();
            objs[8] = dealerVehicleDO.getUniversalUseAmount();
            objs[9] = dealerVehicleDO.getMaintenanceLaveAmount();
            objs[10] = dealerVehicleDO.getUniversalLaveAmount();
            objs[11] = dealerVehicleDO.getIsDisable() == 0 ? "否" : "是";
            objs[12] = dealerVehicleDO.getRemark();
            i = ++i;
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    public void downloadImportExcel() throws Exception {
        FileUtil.downLoadFile(response, filePath, templateExcelFileName);
    }

    public FunctionResult importVehicleExcel(MultipartFile file, String orgId, String userId) throws Exception {
        FunctionResult result = new FunctionResult();
        //Workbook wb = WorkbookFactory.create(in);
        Workbook wb;//同时兼容Excel-2003及Excel-2007
        try {
            InputStream in = file.getInputStream();
            wb = new HSSFWorkbook(in);
        } catch (Exception ex) {
            // 解决read error异常
            // in = new FileInputStream(file);
            InputStream in = file.getInputStream();
            wb = new XSSFWorkbook(in);
        }
        Sheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(1).getLastCellNum();
        if (totalCell != 14) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<CompanyDealerVO> errorDetailVOList = new ArrayList<>();
        boolean success;
        for (int i = 2; i <= totalRow; i++) {
            //HSSFRow curRow=sheet.getRow(i);
            Row curRow = sheet.getRow(i);
            CompanyDealerVO detailVO = new CompanyDealerVO();
            if (curRow == null) {
                continue;
            }
            String dealerCode = getCellValue(curRow, 1);
            if (StringUtil.isNullOrEmpty(dealerCode)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("客户编码不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            String model = getCellValue(curRow, 3);
            if (StringUtil.isNullOrEmpty(model)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("机型不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            String carNo = getCellValue(curRow, 4);
            if (StringUtil.isNullOrEmpty(carNo)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("车号不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            String warrantyStatus = getCellValue(curRow, 5);
            if (StringUtil.isNullOrEmpty(warrantyStatus)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("请填写是否在保");
                errorDetailVOList.add(detailVO);
                continue;
            }
            CompanyDealerDO dealerDO = companyDealerMapper.itemByDealerCode(orgId, dealerCode.trim());
            if (dealerDO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("客户不存在，客户编码：" + dealerCode);
                errorDetailVOList.add(detailVO);
                continue;
            }

            //校验品牌是否存在
            String brandName = getCellValue(curRow, 2);
            if (StringUtils.isNotBlank(brandName)) {
                Integer count = serviceBasicDataAgentService.checkDoesItExistByName(brandName, orgId);
                if (count <= 0) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("品牌不存在：" + brandName);
                    errorDetailVOList.add(detailVO);
                    continue;
                }
            }

            DealerVehicleDO dealerVehicleDO = new DealerVehicleDO();
            DealerVehicleDO dealerVehicleDB = dealerVehicleMapper.getByCarNo(carNo, orgId);

            if(null != dealerVehicleDB) {
                if ( !Integer.valueOf(warrantyStatus).equals(dealerVehicleDB.getWarrantStatus())) {
                    dealerVehicleDB.setWarrantStatus(Integer.valueOf(warrantyStatus));
                    dealerVehicleMapper.update(dealerVehicleDB);
                }
                continue;
            }

            dealerVehicleDO.setClientId(String.valueOf(dealerDO.getId()));
            dealerVehicleDO.setClientName(dealerDO.getCompanyName());
            dealerVehicleDO.setCreateId(userId);
            dealerVehicleDO.setModel(model);
            dealerVehicleDO.setCarNo(carNo);
            dealerVehicleDO.setOrgId(orgId);
            Integer nameCount = dealerVehicleMapper.vehicleCount(dealerVehicleDO);

            if (nameCount > 0) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("客户名下车辆信息已存在，型号：" + model);
                errorDetailVOList.add(detailVO);
                continue;
            }

            dealerVehicleDO.setBrandName(brandName);
            dealerVehicleDO.setCreateId(userId);
            dealerVehicleDO.setCreateDate(new Date());
            dealerVehicleDO.setUpdateId(userId);
            dealerVehicleDO.setUpdateDate(new Date());
            dealerVehicleDO.setMaintenanceSendAmount(StringUtils.isBlank(getCellValue(curRow, 6)) ? BigDecimal.ZERO : new BigDecimal(getCellValue(curRow, 6)));
            dealerVehicleDO.setUniversalSendAmount(StringUtils.isBlank(getCellValue(curRow, 7)) ? BigDecimal.ZERO : new BigDecimal(getCellValue(curRow, 7)));
            dealerVehicleDO.setMaintenanceLaveAmount(StringUtils.isBlank(getCellValue(curRow, 10)) ? BigDecimal.ZERO : new BigDecimal(getCellValue(curRow, 10)));
            dealerVehicleDO.setUniversalLaveAmount(StringUtils.isBlank(getCellValue(curRow, 11)) ? BigDecimal.ZERO : new BigDecimal(getCellValue(curRow, 11)));
            dealerVehicleDO.setMaintenanceUseAmount(StringUtils.isBlank(getCellValue(curRow, 8)) ? BigDecimal.ZERO : new BigDecimal(getCellValue(curRow, 8)));
            dealerVehicleDO.setUniversalUseAmount(StringUtils.isBlank(getCellValue(curRow, 9)) ? BigDecimal.ZERO : new BigDecimal(getCellValue(curRow, 9)));
            dealerVehicleDO.setRemark(getCellValue(curRow, 13));
            dealerVehicleDO.setWarrantStatus(Integer.valueOf(warrantyStatus));
            short isDisable = 0;
            if (StringUtils.isNotBlank(getCellValue(curRow, 12)) && "是".equals(getCellValue(curRow, 12))) {
                isDisable = 1;
            }

            dealerVehicleDO.setIsDisable(isDisable);
            dealerVehicleDO.setId(genClient.newGuidText().getValue());
            success = dealerVehicleMapper.insertSelective(dealerVehicleDO) > 0;
            if (!success) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("新增客户车辆失败，客户编码：" + dealerCode);
                errorDetailVOList.add(detailVO);
            }
        }

        if (errorDetailVOList.isEmpty()) {
            result.setValue(new ArrayList<>());
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }

    private String getCellValue(Row curRow, int i) {
        String value = "";
        if (curRow.getCell(i) != null) {
            curRow.getCell(i).setCellType(CellType.STRING);
            value = curRow.getCell(i).getStringCellValue();
        }
        return value;
    }

    public List<String> getVehicleNoList(String clientName, String orgId) {
        return dealerVehicleMapper.getVehicleNoList(clientName, orgId);
    }

    public DealerVehicleVO getPersonVehicleInfo(String clientName, String orgId, String carNo) {
        DealerVehicleDO vehicleInfo = dealerVehicleMapper.getPersonVehicleInfo(clientName, orgId, carNo);
        DealerVehicleVO vo = null;
        if (null != vehicleInfo) {
            vo = new DealerVehicleVO();
            BeanUtils.copyProperties(vehicleInfo, vo);
        }
        return vo;
    }

    public ErrorCode updateQuota(SalesBillDO salesBillDO, BigDecimal outQuota, String orgId) {
        String useMachineNo = salesBillDO.getSettleMachineNo();
        Short giveQuotaType = salesBillDO.getGiveQuotaType();
        String clientName = salesBillDO.getClientName();
        DealerVehicleDO vehicleDO = dealerVehicleMapper.getAvailableVehicleInfo(clientName, orgId, useMachineNo);
        if (null == vehicleDO) {
            return ErrorCode.IllegalArument;
        }

        DealerVehicleDO dealerVehicleDO = new DealerVehicleDO();
        dealerVehicleDO.setCarNo(useMachineNo);
        dealerVehicleDO.setClientName(clientName);
        if (1 == giveQuotaType) {//通用
            BigDecimal universalUseAmount = vehicleDO.getUniversalUseAmount().add(outQuota).setScale(2, BigDecimal.ROUND_DOWN);
            BigDecimal universalLaveAmount = vehicleDO.getUniversalLaveAmount().subtract(outQuota).setScale(2, BigDecimal.ROUND_DOWN);
            if (universalLaveAmount.compareTo(BigDecimal.ZERO) < 0) {
                LogHelper.error(ErrorCode.TheUsageQuotaIsGreaterThanCreditLimit.getDesc(), ErrorCode.TheUsageQuotaIsGreaterThanCreditLimit.getCode());
                return ErrorCode.TheUsageQuotaIsGreaterThanCreditLimit;
            }
            dealerVehicleDO.setUniversalUseAmount(universalUseAmount);
            dealerVehicleDO.setUniversalLaveAmount(universalLaveAmount);
        }

        if (2 == giveQuotaType) {//保养
            BigDecimal maintenanceUseAmount = vehicleDO.getMaintenanceUseAmount().add(outQuota).setScale(2, BigDecimal.ROUND_DOWN);
            BigDecimal maintenanceLaveAmount = vehicleDO.getMaintenanceLaveAmount().subtract(outQuota).setScale(2, BigDecimal.ROUND_DOWN);
            if (maintenanceLaveAmount.compareTo(BigDecimal.ZERO) < 0) {
                LogHelper.error(ErrorCode.TheUsageQuotaIsGreaterThanCreditLimit.getDesc(), ErrorCode.TheUsageQuotaIsGreaterThanCreditLimit.getCode());
                return ErrorCode.TheUsageQuotaIsGreaterThanCreditLimit;
            }
            dealerVehicleDO.setMaintenanceUseAmount(maintenanceUseAmount);
            dealerVehicleDO.setMaintenanceLaveAmount(maintenanceLaveAmount);
        }
        dealerVehicleDO.setId(vehicleDO.getId());
        dealerVehicleDO.setOldMaintenanceLaveAmount(vehicleDO.getMaintenanceLaveAmount());
        dealerVehicleDO.setOldMaintenanceUseAmount(vehicleDO.getMaintenanceUseAmount());
        dealerVehicleDO.setOldUniversalLaveAmount(vehicleDO.getUniversalLaveAmount());
        dealerVehicleDO.setOldUniversalUseAmount(vehicleDO.getUniversalUseAmount());
        return dealerVehicleMapper.update(dealerVehicleDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode delete(List<String> ids) throws Exception {
        for (String id : ids) {
            //判断车辆是否使用
            DealerVehicleDO dealerVehicleDO = dealerVehicleMapper.selectByPrimaryKey(id);
            if (null == dealerVehicleDO) {
                throw new Exception("车辆信息不存在");
            }
            String orgId = dealerVehicleDO.getOrgId();
            String carNo = dealerVehicleDO.getCarNo();
            String clientName = dealerVehicleDO.getClientName();
            Integer isExists = salesBillMapper.checkCarNoIsExists(orgId, clientName, carNo);
            if (isExists > 0) {
                throw new Exception("车辆:" + carNo + "已被使用不允许删除!");
            }
            dealerVehicleMapper.deleteByPrimaryKey(id);
        }
        return ErrorCode.Success;
    }
}
